package com.hntest.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hntest.entity.*;
import com.hntest.service.BidRequestService;
import com.hntest.service.RealAuthService;
import com.hntest.service.UserFileService;
import com.hntest.service.VedioAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

@Controller("bidRequestController")
public class BidRequestController {

    @Autowired
    private BidRequestService bidRequestService;

    @Autowired
    private RealAuthService realAuthService;

    @Autowired
    private UserFileService userFileService;

    @Autowired
    private VedioAuthService vedioAuthService;
    /*@RequestMapping(value = "/borrow",method = {RequestMethod.GET,RequestMethod.POST})
    public String doselectRequest(BidRequest bidRequest, ModelMap modelMap, HttpServletRequest request){
       *//* HttpSession session = request.getSession(true);
        LoginInfo currUser = (LoginInfo) session.getAttribute("currUser");*//*
        boolean ok = bidRequestService.selectByLoginId(3);
        //modelMap.put("currUser",currUser);
        modelMap.put("ok",ok);
        return "doBorrow";
    }*/

    @RequestMapping(value = "/checkBorrow",method = {RequestMethod.GET,RequestMethod.POST})
    public String checkBrrow(ModelMap modelMap,HttpServletRequest request){
        HttpSession session = request.getSession(true);
        LoginInfo currUser = (LoginInfo) session.getAttribute("currUser");
        RealAuth realAuth = realAuthService.selectByLoginId(currUser.getLid());
        /*if (realAuth!=null){
            modelMap.put("realAuth",realAuth);
        }*/
        modelMap.put("realAuth",realAuth);
        int score = userFileService.getScore(currUser.getLid());
        modelMap.put("score",score);
        VedioAuth vedioAuth = vedioAuthService.selectByLoginId(currUser.getLid());
        modelMap.put("vedioAuth",vedioAuth);

        return "borrowMoney";
    }

    @RequestMapping(value = "/toInsertBorrow",method = {RequestMethod.POST,RequestMethod.GET})
    public String toInsertUserBankInfo(UserBankInfo userBankInfo,ModelMap modelMap,HttpServletRequest request){
        HttpSession session = request.getSession(true);
        LoginInfo currUser = (LoginInfo) session.getAttribute("currUser");
        userBankInfo.setLoginInfo(currUser);

        BidRequest bidRequest = bidRequestService.selectByLoginId(currUser.getLid());
        System.out.println("-------------->>>>"+bidRequest);
        if (bidRequest!=null){
            modelMap.put("bidRequest",bidRequest);
            modelMap.put("ok",false);
        }else {
            //int n = userBankInfoService.insertUserBankInfo(userBankInfo);
            modelMap.put("ok",true);
        }
        return "doBorrow";
    }



    @RequestMapping(value = "/insertBorrow",method = {RequestMethod.GET,RequestMethod.POST})
    public String doInsertRequest(BidRequest bidRequest, ModelMap modelMap,HttpServletRequest request){
        HttpSession session = request.getSession(true);
        LoginInfo currUser = (LoginInfo) session.getAttribute("currUser");
        bidRequest.setCreateUser(currUser);
        /*1，按月到期：因为按月到期本金是最后还，所以每个月产生利息的本金就是借款金额，
        总利息=（年化利息÷12）×借款月数
        2，按月分期：
        1，如果只借一个月：
        总利息=借款金额*（年化利息/12）；
        2，超过一个月：
        每月利息(temp1)=借款金额*月利率； b = xx * c
        借款实际总金额率（temp2）=(1+月利率)^借款月份；(1+c)*monthes2Return = d
        借款实际总利率（temp3）=(1+月利率)^借款月份-1； d -1 = e
        每月还款金额=每月利息*借款实际总金额率/借款实际总利率； b * d /e = f
        总还款金额=每月还款金额*还款月份； f * xx = g
        总利息=总还款金额-借款本金；  (b * (1+c)*monthes2Return /((1+c)*monthes2Return -1))*monthes2Return -bidRequest.getBidRequestAmount() */

        int returnType = bidRequest.getReturnType();
        int monthes2Return = bidRequest.getMonthes2Return();

        if(returnType==0){
            BigDecimal b = bidRequest.getCurrentRate().divide(BigDecimal.valueOf(1200),4, RoundingMode.HALF_UP).multiply(bidRequest.getBidRequestAmount());
           // System.out.println(b);
            BigDecimal c = bidRequest.getCurrentRate().divide(BigDecimal.valueOf(1200),4, RoundingMode.HALF_UP);
            //System.out.println(c);
            if(monthes2Return==1){
                bidRequest.setTotalRewardAmount(b);
            }else {
                BigDecimal d = (c.add(BigDecimal.valueOf(1))).multiply(BigDecimal.valueOf(monthes2Return));
              //  System.out.println(d);
                BigDecimal e = d.subtract(BigDecimal.valueOf(1));
               // System.out.println(e);
                BigDecimal f = b.multiply(d).divide(e, 4, RoundingMode.HALF_UP);
                BigDecimal g = f.multiply(BigDecimal.valueOf(monthes2Return));
               // System.out.println(g);

                bidRequest.setTotalRewardAmount(g);
              //  System.out.println(bidRequest.getTotalRewardAmount()+"xxxxxxxxx");
            }
        }else {
            bidRequest.setTotalRewardAmount( bidRequest.getCurrentRate().divide(BigDecimal.valueOf(1200),4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(monthes2Return)).multiply(bidRequest.getBidRequestAmount()));
           // System.out.println(bidRequest.getTotalRewardAmount());
        }

        //System.out.println(bidRequest.getTotalRewardAmount());

        int n = bidRequestService.insertBidRequest(bidRequest);

        if (n>0){
            //BidRequest bidRequest1 = bidRequestService.selectByLoginId(currUser.getLid());
            //modelMap.put("bidRequest",bidRequest1);
            modelMap.put("ok",false);
        }else {
            modelMap.put("ok",true);
        }
        return "doBorrow";
    }

    @RequestMapping(value = "/admin/selectBidRequest",method = {RequestMethod.GET,RequestMethod.POST})
    public String select(Pager pager, BidRequest bidRequest, ModelMap modelMap){
        List<BidRequest> list = bidRequestService.getListByPage(pager, bidRequest);;
        modelMap.put("list",list);
        modelMap.put("pager",pager);
        modelMap.put("bidRequest",bidRequest);
        String s = "";
        switch (bidRequest.getBidRequestState()){
            case 3:
                s = "admin/selectBidRequest";
                break;
            case 4:
                s = "admin/selectBidRequest2";
                break;
            case 5:
                s = "admin/selectBidRequest3";
                break;
        }
        return s ;
    }


    @RequestMapping(value="/admin/doUpdateBidRequest",method= {RequestMethod.GET,RequestMethod.POST},
            produces= {"application/JSON;charset=utf-8"})
    @ResponseBody
    public Object doUpdateBidRequest(BidRequest bidRequest) {
        System.out.println("-------------------->"+bidRequest.getBidRequestid());
        int n =  bidRequestService.updateBidRequest(bidRequest);
        JSONObject jsonObject = new JSONObject();
        BidRequest bidRequest1 = bidRequestService.selectByBidRequestId(bidRequest.getBidRequestid());

        if (n>0){
            jsonObject.put("success",true);
        }else{
            jsonObject.put("success",false);
            jsonObject.put("msg","系统异常，审核出错");
        }
        jsonObject.put("msg",bidRequest1.getBidRequestStateDisplay());
        return JSON.toJSONString(jsonObject);
    }
}
